﻿using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;

namespace Zhaoxi.MQTTServer
{
    internal class Program
    {
        static IMqttServer server = null;
        static void Main(string[] args)
        {
            Console.WriteLine("欢迎使用朝夕教育MQTT服务器!");

            ServerStart();

            Console.ReadLine();
        }

        private static async void ServerStart()
        {
            server = new MqttFactory().CreateMqttServer();
            // 初始化Sever对象
            server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(Server_ClientConnected);
            server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(Server_ClientSubscribedTopic);
            server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Server_ApplicationMessageReceived);
            //server.StartedHandler
            //server.StoppedHandler
            // 
            // IP  Port  用户名  密码匹配
            MqttServerOptionsBuilder msob = new MqttServerOptionsBuilder()
                .WithDefaultEndpointBoundIPAddress(IPAddress.Any)
                .WithDefaultEndpointPort(1883)// 如果使用其他端口号   无法连接
                .WithConnectionValidator(ConnectionValidator);

            // 生成配置对象
            IMqttServerOptions serverOptions = msob.Build();
            // 根据配置信息启动服务器
            await server.StartAsync(serverOptions);

            Console.WriteLine("服务已启动！");
        }

        private static void ConnectionValidator(MqttConnectionValidatorContext context)
        {
            if (context.Username != "admin" || context.Password != "123456")
            {
                context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;

                Console.WriteLine("ConnectionRefusedBadUsernameOrPassword");
            }
            else
            {
                context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                Console.WriteLine("ConnectionAccepted");

            }
        }

        private static void Server_ClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs e)
        {
            Console.WriteLine(">>> 客户端:" + e.ClientId + "  订阅主题:" + e.TopicFilter.Topic + " - " + e.TopicFilter.QualityOfServiceLevel);
        }

        private static void Server_ClientConnected(MqttServerClientConnectedEventArgs e)
        {
            Console.WriteLine(">>> 客户端:" + e.ClientId + " 连接");
        }

        private static void Server_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {

            if (e.ClientId != null)
            {
                //ushort value = BitConverter.ToUInt16(new byte[] { e.ApplicationMessage.Payload[1],
                //    e.ApplicationMessage.Payload[0] });
                //Console.WriteLine(value);

                // 接收由客户端发过来的消息  这个消息需要分发下去
                Console.WriteLine(">>> 收到消息:" + e.ApplicationMessage.ConvertPayloadToString() + ",来自客户端" + e.ClientId + ",主题:" + e.ApplicationMessage.Topic);
                //转发由客户端发过来的消息 根据主题进行分发
                //server.PublishAsync(e.ApplicationMessage);


            }
        }
    }

}
